package com.spring.service.gf.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.spring.utils.Constants;
import com.spring.utils.StringUtils;
import com.spring.web.formbean.gf.GfSortForm;
import com.spring.bean.gf.GfSort;
import com.spring.dao.gf.GfSortDao;
import com.spring.service.gf.GfSortService;
import com.spring.bean.page.Page;
import com.spring.bean.page.PageView;
import com.spring.service.ServiceSupport;
import com.spring.exception.ServiceException;

@Service
@Transactional
public class GfSortServiceImpl extends ServiceSupport implements GfSortService {

	@Autowired
	private GfSortDao gfSortDao;

	/** insert */
	public boolean insert(GfSortForm gfSortForm) throws ServiceException {
		try{
			GfSort gfSort = formToEntity(GfSort.class, gfSortForm);
			Integer pid = gfSort.getPid();
			// 如果_pid为空，则说明为父级分类
			if(StringUtils.isBlank(pid)){
				pid = Constants.RECORD_PID;
				gfSort.setPid(pid);
			}
			return gfSortDao.insert(gfSort);
		} catch (Exception e) {
			throw new ServiceException("GfSort --- insert error", e);
		}
	}

	/** update */
	public boolean update(GfSortForm gfSortForm) throws ServiceException {
		try{
			GfSort gfSort = formToEntity(GfSort.class, gfSortForm);
			return gfSortDao.update(gfSort);
		} catch (Exception e) {
			throw new ServiceException("GfSort --- update error", e);
		}
	}

	/** delete */
	@Transactional(readOnly=false, rollbackFor=Exception.class)
	public boolean delete(Integer id, Integer pid) throws ServiceException {
		try{
			GfSort sort = gfSortDao.getById(id);
			sort.setIsable(Constants.RECORD_OFF);
			// 如果是_pid,则删除子类后,再删除父类(假删除)
			if(pid == Constants.RECORD_PID){
				List<GfSort> subList = gfSortDao.queryForList(id);
				if(subList != null && subList.size() > 0){
					for(GfSort subSort : subList) {
						subSort.setIsable(Constants.RECORD_OFF);
						gfSortDao.update(subSort);
					}
				}
			} 
			return gfSortDao.update(sort);
		} catch (Exception e) {
			throw new ServiceException("GfSort --- delete error", e);
		}
	}

	/** getById */
	public GfSort getById(Integer id) throws ServiceException {
		try{
			return gfSortDao.getById(id);
		} catch (Exception e) {
			throw new ServiceException("GfSort --- query by id error", e);
		}
	}

	/** queryForList */
	public List<GfSort> queryForList(Integer pid) throws ServiceException {
		try{
			return gfSortDao.queryForList(pid);
		} catch (Exception e) {
			throw new ServiceException("GfSort --- query list error", e);
		}
	}

	/** queryForPage */
	public PageView<GfSort> queryForPage(Page page) throws ServiceException {
		try{
			return gfSortDao.queryForPage(page);
		} catch (Exception e) {
			throw new ServiceException("GfSort ---query page error", e);
		}
	}
}